<?php

namespace App\Http\Controllers;

use App\Models\Business\Business as BusinessModel;
use App\Models\Business\Record as RecordModel;
use App\Models\Business\Pay as PayModel;
use App\Models\Ems as EmsModel;

use Illuminate\Http\Request;
// 引入Validator 门面 
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
// 邮箱
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException;


class Business extends Controller
{

    // 登陆
    public function login()
    {
        $mobile = request('mobile', '');
        $password = request('password', '');
        
        $userinfo = BusinessModel::where('mobile', $mobile)->first();

        if (!$userinfo) {
            return error('当前用户不存在');
        }

        $password = md5($password . $userinfo['salt']);

        if ($password != $userinfo['password']) {
            return  error('密码或用户名错误请重新输入');
        }

        $data = [
            'id' => $userinfo['id'],
            'mobile' => $userinfo['mobile']
        ];

        return success('登陆成功', '', $data);
    }

    // 注册
    public function register()
    {
        $mobile = request('mobile', '');
        $password = request('password', '');

        // 获取密码盐
        $salt = build_ranstr();

        $data = [
            'mobile' => $mobile,
            'password' =>  md5($password . $salt),
            'salt' => $salt,
            'nickname' => $mobile
        ];

        // 验证规则
        $rules = [
            'mobile' => 'required|unique:pre_business',
            'password' => 'required',
            'salt' => 'required'
        ];

        // 错误提示信息
        $message = [
            'mobile.required' => '手机号码必须填写',
            'mobile.unique' => '手机号码已注册，请重新输入',
            'password.required'   => '密码必须填写',
            'salt.required'  => '密码盐必须填写',
        ];

        // make 方法将会生成一个新的验证器实例
        $validator = Validator::make($data, $rules, $message);

        if ($validator->fails()) {
            // errors 获取所有错误信息
            $errors = $validator->errors();
            // first 第一个错误信息;
            return error($errors->first());
        }

        // 用户表验证器校验数据并且添加
        $result = BusinessModel::create($data);

        if ($result === FALSE) {
            return  error('注册失败');
        } else {
            return success('注册成功');
        }
    }

    // 校验
    public function check()
    {
        $id = request('id', '');
        $mobile = request('mobile', '');

        $userinfo = BusinessModel::where(['id' => $id, 'mobile' => $mobile])->first();

        if (!$userinfo) {
            return  error('当前用户不存在');
        }

        $data = [
            'id' => $userinfo['id'],
            'mobile' => $userinfo['mobile'],
            'nickname' => $userinfo['nickname'],
            'avatar' => $userinfo['avatar_text'],
            'gender' => $userinfo['gender'],
            'province' => $userinfo['province'],
            'city' => $userinfo['city'],
            'district' => $userinfo['district'],
            'createtime' => date("Y-m-d H:i:s", strtotime($userinfo['createtime'])),
            'money' => $userinfo['money'],
            'email' => $userinfo['email'],
            'region' => $userinfo['region'],
            'auth' => $userinfo['auth']
        ];

        return success('校验成功', '', $data);
    }

    // 修改个人资料
    public function profile(Request $request)
    {
        $id = request('id', 0);

        $password = request('password', '');

        $params = $request->all();

        $userinfo = BusinessModel::find($id);

        if (!$userinfo) {
            return error('当前用户不存在');
        }

        $data = [
            'nickname' => $params['nickname'],
            'email' => $params['email'],
            'gender' => $params['gender'],
            'province' => $params['province'],
            'city' => $params['city'],
            'district' => $params['district'],
        ];


        // 修改密码
        if (!empty($password)) {
            $password = md5($password . $userinfo['salt']);
            if ($password == $userinfo['password']) {
                return error('修改的密码与原密码一致');
            }
            $data['password'] = $password;
        }

        // 修改头像
        if (isset($_FILES['avatar']) &&  $_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0) {
            $res =  upload('avatar', $request);
            if ($res['code'] == 0) {
                return error($res['msg']);
            }

            $data['avatar'] = $res['msg'];
        }

        $result = BusinessModel::where(['id' => $id])->update($data);

        if ($result === FALSE) {
            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
                $avatar = str_replace("/uploads/", "", $data['avatar']);
                Storage::disk('uploads')->delete($avatar);
            }

            return error('修改失败');

        } else {
            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
                $avatar = str_replace("/uploads/", "", $userinfo['avatar']);
                Storage::disk('uploads')->delete($avatar);
            }

            $userinfo =  BusinessModel::find($id);

            // 封装cookie数据
            $datas = [
                'id' => $userinfo['id'],
                'mobile' => $userinfo['mobile'],
                'nickname' => $userinfo['nickname'],
                'avatar' => $userinfo['avatar_text'],
                'gender' => $userinfo['gender'],
                'province' => $userinfo['province'],
                'city' => $userinfo['city'],
                'district' => $userinfo['district'],
                'createtime' => date("Y-m-d H:i:s", strtotime($userinfo['createtime'])),
                'money' => $userinfo['money'],
                'email' => $userinfo['email'],
                'region' => $userinfo['region'],
                'auth' => $userinfo['auth']
            ];

            return success('修改成功', '', $datas);
        }
    }

    // 获取消费记录
    public function record()
    {
        $busid = request('busid', 0);

        $userinfo =  BusinessModel::find($busid);

        if (!$userinfo) {
            return error('当前用户不存在');
        }

        $data = RecordModel::where(['busid' => $busid])->whereIn('state', ['2', '3'])->orderBy('createtime', 'desc')->get();

        return success('', '', $data);
    }

    // 充值
    public function recharge()
    {
        //获取所有的参数
        $point = request('point', 0);

        $busid = request('busid', 0);

        $content = request('content', '');

        $userinfo =  BusinessModel::find($busid);

        if (!$userinfo) {
            return error('用户不存在');
        }

        $data = [
            'busid' => $busid,
            'point' => $point,
            'status' => '0',
            'content' => $content
        ];

        // 验证规则
        $rules = [
            'busid' => 'required',
            'point' => 'required'
        ];

        // 错误提示信息
        $message = [
            'busid.required'     => '用户ID必须填写',
            'proid.required' => '充值金额必须填写'
        ];

        $validator = Validator::make($data, $rules, $message);

        if ($validator->fails()) {
            // errors 获取所有错误信息
            $errors = $validator->errors();
            // first 第一个错误信息;
            return error($errors->first());
        }

        $result = PayModel::create($data);

        if ($result === FALSE) {
            return error('充值失败');
        } else {
            return success('充值成功,待审核');
        }
    }

    // 充值记录
    public function rechargerecord()
    {

        $busid = request('busid', 0);

        $userinfo =  BusinessModel::find($busid);

        if (!$userinfo) {
            return error('用户不存在');
        }

        $result = PayModel::where(['busid' => $busid])->orderBy('createtime', 'desc')->get();

        return success('充值记录列表', null, $result);
    }

    // 发送邮箱验证码
    public function emailcode(\Exception $e)
    {
        $busid = request('busid', 0);

        $email = request('email', '');

        $userinfo =  BusinessModel::find($busid);

        if (!$userinfo) {
            return error('当前用户不存在');
        }

        if ($email != $userinfo['email']) {
            return error('不是当前用户邮箱');
        }

        // 校验用户是否在发送过验证码
        $Emslist = EmsModel::where(['email' => $email])->first();

        if ($Emslist) {
            $updatetime = strtotime($Emslist['createtime']) + 120;
            if (time() < $updatetime) {
                return error('两分钟之内发送过验证码，请去邮箱查看');
            } else {
                $EmsStatus = EmsModel::destroy($Emslist['id']);
                if (!$EmsStatus) {
                    return error('验证码发送失败');
                }
            }
        }

        // 生成验证码
        $code = build_ranstr(4);

        DB::beginTransaction();

        try {

            $data = [
                'event' => 'vue商城校验用户邮箱',
                'email' => $email,
                'code' => $code,
                'times' => 1
            ];

            $result = EmsModel::create($data);

            if ($result === false) {
                return error($e->getMessage());
            }

            // 发送邮件其次我们可以设置邮件主题正文、接收者、标题等信息，比如
            Mail::raw("验证码：$code", function ($message) use ($email) {
                $message->to($email)->subject('验证用户邮箱');
            });

            DB::commit();
            return success('验证码发送成功');
        } catch (QueryException $ex) {
            DB::rollback();
            return error($ex->getMessage());
        }
    }

    // 校验邮箱
    public function attestation(\Exception $e)
    {
        $busid = request('busid', 0);

        $email = request('email', '');

        $code = request('code', '');

        $userinfo = BusinessModel::find($busid);

        if (!$userinfo) {
            return error('当前用户不存在');
        }

        if ($email != $userinfo['email']) {
            return error('不是当前用户邮箱');
        }

        if (empty($code)) {
            return error('邮箱验证码不能为空');
        }

        $res = EmsModel::where(['email' => $email, 'code' => $code])->first();

        if (!$res) {
            return error('验证码错误，请重新填写');
        }

        $updatetime = strtotime($res['createtime']) + 120;
        if (time() > $updatetime) {
            return error('验证码已过期，请重新填写');
        }

        // 开启事务
        DB::beginTransaction();

        try {

            $Businessdata = [
                'auth' => '1'
            ];

            $BusinessStatus = BusinessModel::where(['id' => $busid])->update($Businessdata);
            if ($BusinessStatus === false) {
                return error($e->getMessage());
            }

            $EmsStatus = EmsModel::destroy($res['id']);

            if ($EmsStatus === false) {
                return error($e->getMessage());
            }

            DB::commit();
            return success('邮箱认证成功');
        } catch (QueryException $ex) {
            DB::rollback();
            return error('邮箱认证失败');
        }
    }
}
